package com.lagou.oss.web;

import com.lagou.oss.service.AliyunUploader;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName OSSController
 * @Description TODO
 * @Author xsq
 * @Date 2020/9/22 10:32
 **/
@RestController
@RequestMapping(value = "/oss")
public class OSSController {

    @Autowired
    private AliyunUploader aliyunUploader;

    private static final String[] allowExts = {"png","jpeg","jpg"};

    @PostMapping(value = "/upload")
    public String upload(MultipartFile file) throws IOException {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if(!isAllow(extension)){
            return "当前文件格式不支持";
        }
        String objectName = UUID.randomUUID().toString().replaceAll("-","")+"."+extension;
        aliyunUploader.upload(file.getBytes(),objectName);
        return objectName;
    }

    @GetMapping(value = "/download")
    public void download(@RequestParam String objName, HttpServletResponse response) throws IOException{
        byte[] fileBytes = aliyunUploader.download(objName);
        String extension = FilenameUtils.getExtension(objName);
        response.setContentType("image/"+extension);
        ServletOutputStream os = response.getOutputStream();
        os.write(fileBytes);
        os.flush();
        os.close();
    }

    @DeleteMapping(value = "/delete")
    public String delete(@RequestParam String objName){
        aliyunUploader.delete(objName);
        return "success";
    }

    private static boolean isAllow(String ext){
        for (String allowExt : allowExts) {
            if(StringUtils.equalsAnyIgnoreCase(allowExt,ext)){
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) {
        System.out.println(isAllow("jpg"));
    }
}